
import 'package:bookshelf/entity/book_entity.dart';
import 'package:bookshelf/entity/classify_entity.dart';
import 'package:bookshelf/http/api.dart';
import 'package:bookshelf/page/book_page.dart';
import 'package:bookshelf/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../http/api_url.dart';
import '../main.dart';
import '../widget/app_bar.dart';
import '../util/timer_manager.dart';

class Search extends StatefulWidget {
  const Search({Key? key}) : super(key: key);

  @override
  State<Search> createState() => _SearchState();
}

class _SearchState extends State<Search> {


  final RxList<BookEntity> _list = RxList();
  final RxList<ClassifyEntity> _classifyList = RxList();

  String keyword ='';

  RxBool isSelf = true.obs;

  RxBool isGrid = false.obs;

  RxInt tab = 0.obs;

  var page = 1;

  final ScrollController _scrollController = ScrollController();


  @override
  initState() {
    super.initState();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        page++;
        _loadMore(_classifyList[tab.value].name);
      }
    });

    WidgetsBinding.instance.addPostFrameCallback((_){
      timer.startCountDown(CountDownMode.action, (){
        timer.cancel();
        Get.until((route) => route.isFirst);
      });
    });
    _loadMore(null);
    _initClassify();

  }

  _initClassify() {
    _classifyList.clear();
    _classifyList.add(ClassifyEntity()
      ..remark='全部书籍'
      ..name=null);
    classify().then((value){
      if(value != null){
        _classifyList.addAll(value);
      }
    });

  }

  _loadMore(String? classify) async {

    var range = '';
    if(isSelf.value){
      range = '${settingEntity.roomNo}${settingEntity.columnNo}';
    }else{
      range = '';
    }
    classify ??= '';
    var list = await search(range,page,classify: classify,keyword: keyword);
    if(page == 1){
      _list.clear();
    }
    if(list != null){
      if(list.isEmpty){
        // toastWarn('没有更多数据');
        return;
      }
      _list.addAll(list);
    }
  }

  _tab(){
    return  Obx(() => Container(
      margin: EdgeInsets.only(top: 4.h,left: 8.w,right: 8.w),
      height: 20.h,
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _tabWidget(index);
        },
        scrollDirection: Axis.horizontal,
        itemCount: _classifyList.length,
     ),))
    ;
  }

  _tabWidget(index){
    var item = _classifyList[index];
    return Obx(() => InkWell(
      onTap: (){
        tab.value = index;
        page = 1;
        _loadMore(_classifyList[tab.value].name);
      },
      child: Container(
        padding: EdgeInsets.only(left: 3.w,right: 3.w),
        alignment: Alignment.center,
        child: Text('${item.remark}',style: TextStyle(color: Colors.transparent,fontSize: 8.sp,fontWeight: tab.value==index?FontWeight.bold:FontWeight.normal,
            shadows: [Shadow(color: Colors.white, offset: Offset(0, tab.value==index?-5:-8))],
            decoration: tab.value==index?TextDecoration.underline:TextDecoration.none,decorationColor:Colors.deepOrangeAccent,decorationThickness: 2),),
      )
    ));
  }

  _title(){
    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(top: 10.h,left: 8.w,right: 8.w),
      child: Stack(
        alignment: AlignmentDirectional.centerStart,
        children: [
          InkWell(
            onTap: (){
              timer.cancel();
              Get.back();
            },
            child: Image.asset("assets/images/back.png",width:50.w,fit: BoxFit.fitWidth,)
          ),
          Positioned(left:40.w,child: Align(child: _searchBarWidget())),
          Positioned(right:38.w,child: Obx(() => InkWell(
            onTap: (){
              isSelf.value = !isSelf.value;
              page = 1;
              _loadMore(_classifyList[tab.value].name);
            },
            child: Image.asset("assets/images/${isSelf.value?'self':'all'}.png",width:54.w,fit: BoxFit.fitWidth,)),
          ),),
          Positioned(right:40,child: Obx(() =>InkWell(
            onTap: (){
              isGrid.value = !isGrid.value;
            },
            child: Image.asset("assets/images/${isGrid.value?'grid':'list'}.png",width:20.w,fit: BoxFit.fitWidth,),
          ),)),
          Positioned(right:0,child: Obx(() => Text("${timer.actionTime.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),)),)
        ],
      )
    );
  }

  _searchBarWidget(){
    return Container(
        decoration:BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(16.r)),
        ),
        padding: EdgeInsets.only(left: 4.w,right: 1.5.w,top: 1.5.h,bottom: 1.5.h),
        margin:  EdgeInsets.only(left: 20.w, right: 20.w, bottom: 15.h,top: 15.h),
        child: Row(
          children: [
            const Icon(Icons.search),
            SizedBox(width: 4.w,),
            SizedBox(
              width: 174.w,
              child: TextField(
                  minLines: 1,
                  textInputAction: TextInputAction.search,
                  onSubmitted: (input){
                    page = 1;
                    _loadMore(_classifyList[tab.value].name);
                  },
                  onChanged: (input){
                    keyword = input;
                  },
                  decoration: InputDecoration(
                    contentPadding: EdgeInsets.only(top: 1.h,bottom: 1.h),
                    isCollapsed: true,
                    border: InputBorder.none,
                    hintText: "按 书名 作者",
                  ),
                  style: TextStyle(color: Colors.black,fontSize: 8.sp)
              ),

            ),
            InkWell(
              onTap: (){
                page = 1;
                _loadMore(_classifyList[tab.value].name);
              },
              child: Image.asset("assets/images/search.png",width: 30.w,fit: BoxFit.fitWidth,),
            )
          ],
        )
    );
  }

  _gridBooks(){
    return  Obx(() => Container(
      margin: EdgeInsets.only(left: 8.w,right: 8.w),
      padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 10.h,bottom: 10.h),
      height: 610.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      child: GridView.builder(
        itemBuilder: (context, index) {
          return _gridBuilder(index);
        },
        itemCount: _list.length,
        controller: _scrollController,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4,childAspectRatio:0.76,  crossAxisSpacing: 8.w, mainAxisSpacing: 8.h),
      ),
    ));
  }


  _gridBuilder(index){
    var item = _list[index];
    return InkWell(
      onTap: (){
        Get.to(()=> const Book(),arguments: item);
      },
      child: Column(
        children: [
          Image.network('$apiUrl/${item.coverFileUrl}',width: 77.w,height:98.h,fit: BoxFit.fill,
            errorBuilder: ( BuildContext context, Object error, StackTrace? stackTrace,){
              return  Image.asset('assets/images/default.png',width: 77.w,height:98.h,fit: BoxFit.fill);
            },
          ),
          Text('${item.mainTitle}',style: TextStyle(color: Colors.black,fontSize: 8.sp),maxLines: 1,),
        ],
      ),
    );
  }

  _listBooks(){
    return  Obx(() => Expanded(child: ListView.builder(
      itemBuilder: (context, index) {
        return _listBuilder(index);
      },
      itemCount: _list.length,
      controller: _scrollController,
    )));
  }
  _listBuilder(index){
    var item = _list[index];
    RxBool showAnimation = false.obs;
    RxInt recommendCount = (item.resort??0).obs;
    return InkWell(
      onTap: (){
        Get.to(()=> const Book(),arguments: item);
      },
      child: Container(
          margin: EdgeInsets.only(bottom: 5.r,left: 8.r,right: 8.r),
          padding: EdgeInsets.only(top: 5.r,bottom:5.r,left: 8.r,right: 8.r),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(4.r)),
          ),
          child: Stack(
            children: [
              Positioned(child: Image.network('$apiUrl/${item.coverFileUrl}',width: 67.w,height:90.h,fit: BoxFit.fill,
                errorBuilder: ( BuildContext context, Object error, StackTrace? stackTrace,){
                  return  Image.asset('assets/images/default.png',width: 67.w,height:90.h,fit: BoxFit.fill);
                },),),
              Positioned(left:80.w,top:6.h,right:50.w,
                child: SingleChildScrollView(
                  scrollDirection: Axis.horizontal,
                  child: Text('《${item.mainTitle}》',maxLines:1,style: TextStyle(color: Colors.black,fontSize: 10.sp,fontWeight: FontWeight.bold),),
                )
              ),
              if(item.place != null && item.place!.isNotEmpty)...[
                Positioned(right:12.w,top:8.h,child: Image.asset("assets/images/there.png",width: 30.w,fit: BoxFit.fitWidth)),
              ],
              Positioned(left:80.w,top:20.h,child: Text('${item.author}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
              Positioned(left:80.w,top:35.h,child: InkWell(
                onTap: (){
                  resort.addByNo(item.no);
                  recommendCount.value = recommendCount.value +1;
                  item.resort = recommendCount.value;
                  if(!showAnimation.value){
                    showAnimation.value = true;
                    Future.delayed(const Duration(milliseconds: 300),(){
                      showAnimation.value = false;
                    });
                  }
                },
                child: Image.asset("assets/images/like_click.png",width: 40.w,fit: BoxFit.fitWidth)
              ),),
              Positioned(left:90.w,top:5.h,child:  Obx(() => InkWell(
                onTap: () {
                  resort.addByNo(item.no);
                  recommendCount.value = recommendCount.value +1;
                  item.resort = recommendCount.value;
                  if(!showAnimation.value){
                    showAnimation.value = true;
                    Future.delayed(const Duration(milliseconds: 300),(){
                      showAnimation.value = false;
                    });
                  }
                },
                child: Visibility(visible:showAnimation.value,child: Image.asset("assets/images/star.gif",width: 40.w,fit: BoxFit.fitWidth))
              ),),),
              Positioned(left:115.w,top:30.h,child: Container(
                width: 10.w,
                height: 10.w,
                alignment: Alignment.center,
                decoration:  BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(44.r)),
                    color: const Color.fromRGBO(255, 0, 0, 1)
                ),
                child: Obx(() => Text('${recommendCount.value>999?'999+':recommendCount.value}',style: TextStyle(color: Colors.white, fontSize: 4.sp),)),
              )),
              Positioned(left:80.w,top:50.h,child: Text('位置：${item.placeName}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
              Positioned(left:80.w,top:62.h,child: Text('索书号：${item.searchNo} ',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
              Positioned(left:80.w,top:74.h,child: Text('条码：${item.no}',style: TextStyle(color: Colors.black,fontSize: 8.sp),),),
            ],
          )
      ),
    );
  }

  // _analyzePlace(String? place){
  //   if(place == null){
  //     return '';
  //   }
  //   String room = place.substring(0,2);
  //   String column = place.substring(2,6);
  //   String side = place.substring(6,8);
  //   String knot = place.substring(8,10);
  //   String floor = place.substring(10,12);
  //   return '$room区$column列${side=='01'?'A面':'B面'}$knot节$floor层';
  // }

  _recommendDialog(){
    var name = '';
    var reason = '';
    Get.defaultDialog(
      title: "",
      contentPadding:EdgeInsets.zero,
      titlePadding:EdgeInsets.zero,
      backgroundColor: Colors.transparent,
      content: Container(
        width: 320.w,
        height: 338.h,
        decoration: const BoxDecoration(
            image: DecorationImage(
              fit: BoxFit.fill,
              image: AssetImage(
                "assets/images/recommend_bg.png",
              ),
            )
        ),
        child: Stack(
          alignment: Alignment.topCenter,
          children: [
            Positioned(
                right: 10.w,
                child: InkWell(
                  onTap: (){
                    Get.back();
                  },
                  child: Container(
                      height: 30.h,
                      alignment: Alignment.center,
                      child: Icon(Icons.close,color: Colors.white,size: 18.sp,)
                  ),
                )
            ),
            Positioned(
                top: 140.h,
                left: 45.w,
                child: Text('推荐书名',style: TextStyle(color: Colors.black,fontSize: 8.sp),)
            ),
            Positioned(
              top: 155.h,
              left: 45.w,
              right: 45.w,
              child:  Container(
                decoration: BoxDecoration(
                  color: const Color.fromRGBO(230, 230, 230, 1),
                  borderRadius: BorderRadius.all(Radius.circular(4.r)),
                ),
                child: TextField(
                  decoration:  InputDecoration(
                    border:  InputBorder.none,
                    contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
                  ),
                  style: TextStyle(fontSize: 8.sp),
                  onChanged: (value){
                    name = value;
                  },
                ),
              ),
            ),
            Positioned(
                top: 190.h,
                left: 45.w,
                child: Text('推荐理由',style: TextStyle(color: Colors.black,fontSize: 8.sp),)
            ),
            Positioned(
              top: 205.h,
              left: 45.w,
              right: 45.w,
              child:  Container(
                decoration: BoxDecoration(
                  color: const Color.fromRGBO(230, 230, 230, 1),
                  borderRadius: BorderRadius.all(Radius.circular(4.r)),
                ),
                child: TextField(
                  decoration:  InputDecoration(
                    border:  InputBorder.none,
                    contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 5, bottom: 5).r,
                  ),
                  style: TextStyle(fontSize: 8.sp),
                  onChanged: (value){
                    reason = value;
                  },
                ),
              ),
            ),
            Positioned(
              top: 260.h,
              left: 45.w,
              right: 45.w,
              child: InkWell(
                onTap: (){
                  if(name.isEmpty){
                    toastWarn('请填写书名');
                    return;
                  }
                  suggest(name,reason).then((value){
                    if(value){
                      toastWarn('提交成功');
                    }
                  });
                  Get.back();
                },
                child: Image.asset("assets/images/btn_recommend.png",width: 120.w,fit: BoxFit.fitWidth),
              ),
            ),

          ],
        ),
      ),
    );
  }

  _empty(){
    return Container(
      margin: EdgeInsets.only(left: 8.w,right: 8.w),
      padding: EdgeInsets.only(left: 10.w,right: 10.w,top: 10.h,bottom: 10.h),
      height: 610.h,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
      alignment: Alignment.center,
      child: Stack(
        alignment: AlignmentDirectional.center,
        children: [
          Positioned(
            top: 70.h,
            child: Image.asset("assets/images/empty.png",width: 300.w,fit: BoxFit.fitWidth),
          ),
          Positioned(
            top: 370.h,
            child:  InkWell(
              onTap: (){
                if(isSelf.value){
                  isSelf.value = false;
                }else{
                  _recommendDialog();
                }
              },
              child: Obx(() => Text(isSelf.value?'未搜索到图书，点击切换搜索全馆':'未搜索到图书，点击可向馆方推荐图书',style: TextStyle(color: Colors.transparent,fontSize: 8.sp,fontWeight: FontWeight.normal,
                  shadows: const [Shadow(color: Colors.deepOrangeAccent, offset: Offset(0, -5))],
                  decoration: TextDecoration.underline,decorationColor:Colors.deepOrangeAccent,decorationThickness: 2),)),
            ),
          ),

        ],
      ),
    );
  }


  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () => FocusScope.of(context).requestFocus(FocusNode()),
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        body: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: const BoxDecoration(
            image: DecorationImage(
              fit: BoxFit.fill,
              image: AssetImage(
                "assets/images/bg.png",
              ),
            ),
          ),
          child: Column(
            children: [
              appBar(),
              _title(),
              _tab(),
              Obx(() => _list.isEmpty?_empty():isGrid.value?_gridBooks():_listBooks()),
            ],
          ),
        ),
      ),
    );
  }
}

